/*
 * @Description  : git 相关请求
 * @Autor        : yanwang
 * @CreateDate   : 2023-05-23 14:22:05
 * @LastEditors  : yanwang
 * @LastEditTime : 2023-05-25 17:10:20
 */

// const axios = require('axios');
const downloadGitRepo = require('download-git-repo'); // 拉取模板
const { promisify } = require('util');
const { CLICONFIG } = require('./constants');
// const { config } = require('process');
// const config = require('./config');

const downloadGit = promisify(downloadGitRepo);

// 获取项目分支列表
const fetchTemplates = async () => {
  // const { data } = await axios.get('https://gitlab.moji.com/api/v4/projects/3675/repository/branches');
  // return data;
  const configApi = 'gitlab.moji.com:moji-fe/moji-cli/-/archive/master';
  try {
    await downloadGit(configApi, CLICONFIG);
    const config = require(`${CLICONFIG}/config.js`);
    return config.templates;
  } catch (e) {
    console.log('\n获取cli配置失败\n');
    // console.log('获取云端config配置失败, 使用默认config');
    // const config = require('./config');
    // return config.templates;
    return null;
  }
};

// 获取代码
const downloadTemplate = async (curTemplate, dest) => {
  const api = `gitlab.moji.com:${curTemplate.respositoyUrl}/-/archive/${curTemplate.branch || curTemplate.tag || 'master'}`;
  return downloadGit(api, dest);
};

module.exports = {
  fetchTemplates,
  downloadTemplate,
};
